import os
import sys
import pylab as plt
import numpy as np

from params import *

fig_width_pt = 246.0  # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27               # Convert pt to inch
golden_mean = (plt.sqrt(5)-1.0)/2.0         # Aesthetic ratio
fig_width = fig_width_pt*inches_per_pt  # width in inches
fig_height = fig_width*golden_mean      # height in inches
fig_size =  [fig_width,fig_height]
params = {'backend': 'ps',
        'axes.labelsize': 20,
        'text.fontsize': 20,
        'legend.fontsize': 20,
        'xtick.labelsize': 20,
        'ytick.labelsize': 20,
        'text.usetex': True,
        'figure.figsize': fig_size}
plt.rcParams.update(params)
cities = ['Washington', 'Los Angeles', 'New York', 'Chicago', 'San Jose',
        'Dallas', 'Seattle', 'Atlanta', 'Miami', 'Phoenix', 'Frankfurt', 
        'London', 'Amsterdam', 'Tokyo', 'Toronto', 'Paris', 'Hong Kong', 
        'Singapore', 'Sydney']

servers = [552, 523, 438,
        374,372,195,151,111,111,3,314,300,199,126,121,120,83,53,1]

server_size = dict((a,b) for a,b in zip(cities,servers)) 
total_size = sum(servers)

DIR = os.path.join(WORKDIR, 'gsn', 'cpp', 'limelight', 'results')
def extract_params(filename):
    try:
        params = filename[:-4].split('_')
        cache, weight,size = map(int,params[2:5])
        traffic_prob = float(params[5])
        retweet = float(params[6])
        r = {}
        r['cache_mode'] = cache
        r['weight_mode'] = weight
        r['cache_size'] = size
        r['traffic_ratio'] = traffic_prob
        r['retweet'] = retweet

        return r
    except:
        return None

data = {}
for file in os.listdir(DIR):
    params = extract_params(file)
    if not params:
        continue
    cache_mode = params['cache_mode']
    weight_mode = params['weight_mode']
    retweet_ratio = params['retweet']

    size = params['cache_size']
    if cache_mode != 0:
        continue
    if weight_mode != 0:
        continue
    if size != 100:
        continue
    if retweet_ratio != 0.005:
      continue
    total_hits = 0
    total_misses = 0
    total_cold = 0
    first = True
    stats = {}
    total_requests = 0
    for line in open(os.path.join(DIR,file)):
        if first:
            first = False
            num_req, num_videos = map(int,line.split(';'))
            continue

        server,name,hits,misses,cold_misses = line.split(';')
        h,m,c = map(int,(hits,misses,cold_misses))
        stats[name] = h+m
        total_requests += h+m

    data = []
    for server in stats:
        f = 100.0*stats[server]/total_requests
        f2 = 100.0*server_size[server]/total_size
        data.append((f,f2,server))

    data.sort()
    print data
    y,y2 = [],[]
    lbl = []
    for f,f2,server in data:
        y.append(f)
        y2.append(f2)
        lbl.append(server)

    # definitions for the axes
    left, width = 0.2, 0.75
    bottom, height = 0.1, 0.85

    rect_scatter = [left, bottom, width, height]

    # start with a rectangular Figure
    plt.figure(1, figsize=(8,8))
    #plt.clf()
    #plt.axes(FIG_AXES)
    axPlot = plt.axes(rect_scatter)

    height = 0.3
    numSize = len(y)
    pos = 1 + np.arange(numSize) - height/2
    pos2 = 1 + np.arange(numSize) + height/2
    pos_ticks = pos

    rects1 = axPlot.barh(pos, y, align='center', height=height, color='0.2')
    rects2 = axPlot.barh(pos2, y2, align='center', height=height, color='0.8')
    plt.yticks(pos_ticks,lbl)
    plt.legend([rects1[0],rects2[0]],['Requests','Servers'],
            loc='lower right')
    [x1,x2,y1,yy] = plt.axis()
    plt.axis([x1,x2,0,numSize+1])
    plt.xlabel('Fraction [\%]')
    plt.grid(True)
    #plt.savefig('stat_server_hits_%d_%d_%d_%f.pdf'%(
    #    cache_mode, weight_mode, size, retweet_ratio))
    plt.savefig('server_hits.pdf')
    plt.close()
